import {Component, OnInit} from '@angular/core';
import {changeTheme, ConfigKey, getObj, getUser, removeUser, saveObj, saveUser} from '../../util/app.util';
import {UserService} from '../../service/user.service';
import {DomSanitizer} from '@angular/platform-browser';
import {ConfigService} from '../../service/config.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
  webHeadImgUrl: any;

  constructor(
    private router: Router, private sanitization: DomSanitizer,
    public userService: UserService, private configService: ConfigService) {
  }

  ngOnInit() {
    // 初始化config
    this.configService.userConfig = getObj();
    // 初始化user
    this.userService.user = getUser();
    // 监听user的改变
    this.userService.userChangeEvent.subscribe(user => {
      if (user) {
        saveUser(user);
        this.userService.user = user;
        // this.configService.userConfigEvent.emit(null);
        this.router.navigate(['/home']);
      } else {
        this.userService.user = null;
        removeUser();
        this.router.navigate(['/auth/login']);
      }
    });
    // 监听页面的改变，获取用户配置
    this.configService.userConfigEvent.subscribe(config => {
      this.configService.getUserConfig(this.userService.user.token).subscribe(userConfig => {
        saveObj(ConfigKey, userConfig);
        this.configService.userConfig = userConfig;
        this.webHeadImgUrl = this.sanitization.bypassSecurityTrustStyle(`url('${userConfig.webHeadImg}')`);
      });
    });
  }

  changeTheme(theme: string) {
    changeTheme(theme);
  }
}
